#include "GLAllInOne.h"
#include "Transform.h"

namespace ManchyGL
{
	Transform::Transform()
	{
		_position = vec3(0.0f);
		_rotation = vec3(0.0f);
		_scale = vec3(1.0f);
		_matrix = mat4(1.0f);

		_forward = vec3(0.0f,0.0f,1.0f);
		_up = vec3(0.0f, 1.0f, 0.0f);
		_right = vec3(1.0f, 0.0f, 0.0f);
	}

	void Transform::SetPosition(vec3 value)
	{
		_position = value;
		_isDirty = true;
	}

	vec3 Transform::GetPosition()
	{
		return _position;
	}

	void Transform::SetRotation(vec3 value)
	{
		_rotation = value;
		_isDirty = true;
	}

	vec3 Transform::GetRotation()
	{
		return _rotation;
	}

	void Transform::SetScale(vec3 value)
	{
		_scale = value;
		_isDirty = true;
	}

	vec3 Transform::GetScale()
	{
		return _scale;
	}

	vec3 Transform::GetForward()
	{
		TryUpdateMatrix();
		return _forward;
	}

	vec3 Transform::GetRight()
	{
		TryUpdateMatrix();
		return _right;
	}

	vec3 Transform::GetUp()
	{
		TryUpdateMatrix();
		return _up;
	}

	mat4 Transform::GetMatrix()
	{
		TryUpdateMatrix();
		return _matrix;
	}

	void Transform::TryUpdateMatrix()
	{
		if (!_isDirty) return;
		_isDirty = false;

		mat4 mat = mat4(1.0f);
		mat4 rotateMat = glm::rotate(mat, glm::radians(_rotation.z), vec3(0.0f, 0.0f, 1.0f))
			* glm::rotate(mat, glm::radians(_rotation.x), vec3(1.0f, 0.0f, 0.0f))
			* glm::rotate(mat, glm::radians(_rotation.y), vec3(0.0f, 1.0f, 0.0f));

		_forward = rotateMat * vec4(0.0f, 0.0f, 1.0f, 0.0f);
		_up = rotateMat * vec4(0.0f, 1.0f, 0.0f, 0.0f);
		_right = rotateMat * vec4(1.0f, 0.0f, 0.0f, 0.0f);
		_matrix = glm::translate(mat, _position) * rotateMat * glm::scale(mat, _scale);
	}
}